﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FtpCrawler;
using Lucene.Net.Analysis.Cn;
using Lucene.Net.Documents;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;

namespace LuceneSearcher
{
    public class MainSearcher
    {
        private int _count;    // 搜索结果数目
        private TimeSpan elapsedTime;    // 搜索时间

        public int Count
        {
            get { return _count; }
            set { _count = value; }
        }

        public TimeSpan ElapsedTime
        {
            get { return elapsedTime; }
            set { elapsedTime = value; }
        }

        /// <summary>
        /// 查询Lucene索引
        /// </summary>
        /// <param name="strKey">查询关键字</param>
        /// <returns>返回查询结果列表</returns>
        public FtpFileInfo[] Search(string indexPath, string strKey)
        {
            DateTime startTime = DateTime.Now;

            IndexSearcher searcher = new IndexSearcher(indexPath);
            Query query = (new QueryParser("Filename", new ChineseAnalyzer())).Parse(strKey);

            Hits hits = searcher.Search(query);
            this.Count = hits.Length();

            List<FtpFileInfo> files = new List<FtpFileInfo>();
            Document doc = null;
            FtpFileInfo fileInfo = null;
            for (int i = 0; i < hits.Length(); i++)
            {
                doc = hits.Doc(i);
                string id = doc.Get("Id");
                string isFile = doc.Get("IsFile");
                string filename = doc.Get("Filename");
                string path = doc.Get("Path");

                fileInfo = new FtpFileInfo();
                fileInfo.Id = int.Parse(id);
                fileInfo.IsFile = Int16.Parse(isFile) == 1 ? true : false;
                fileInfo.Filename = filename;
                fileInfo.Path = path;
                files.Add(fileInfo);
            }


            this.elapsedTime = DateTime.Now - startTime;

            return files.ToArray();
        }
    }
}
